//注册方法

import {reactive, ref} from "vue";
import {register} from '../axios/API'
import {ElMessage} from "element-plus";
import fa from "element-plus/packages/locale/lang/fa";

export default function () {
    //控制注册对话框是否显示
    let dialogFormVisible = ref(false)
    //表单标记
    let registerForm = ref(null)
    //表单信息
    let userInfo = reactive({
        username: '',
        password: '',
        telNumber: '',
        email: ''
    })
    //表单检验规则
    let registerFormRules = reactive({
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        telNumber: [{required: true, message: '请输入电话号', trigger: 'blur'}],
        email: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
    })

    //注册表单提交
    function registerFormSub() {
        registerForm.value.validate(async (valid) => {
            if (valid) {
                //准备注册
                let {data} = await register(userInfo)
                if (data.status + '' === '200') {
                    //注册成功
                    ElMessage.success('注册成功')
                    //关闭对话框
                    dialogFormVisible.value = false

                } else if (data.status + '' === '999') {
                    //注册失败
                    ElMessage.error(`注册失败，原因：${data.info}`)
                } else {
                    //未知错误
                    ElMessage.error('未知错误，请联系管理员。')
                }
            }
        })
    }

    //对话框关闭时的回调函数
    function clearData() {
        userInfo.username = ''
        userInfo.password = ''
        userInfo.email = ''
        userInfo.telNumber = ''
    }


    return {
        dialogFormVisible, userInfo, registerForm, registerFormRules, registerFormSub, clearData
    }
}
